const beijingTime = require("../tools/timer");
const baseCode = require("../tools/baseCode");
const { Register } = require("../schema");
const { successMessage, failMessage, errMessage } = require("../tools/message");
/**
 * 系统录入
 */
exports.register = (Router) => {
	Router.post("/register", async (req, res) => {
		try {
			const requiredFields = ["root", "pwd", "user"];
			const missingFields = requiredFields.filter(
				(field) => !req.body[field] || req.body[field].trim() === ""
			);

			if (missingFields.length) {
				failMessage(req, res, "不能留空");
				return;
			}
			if (req.body.pwd !== req.body.pwd2) {
				failMessage(req, res, "密码不一致");
				return;
			}
			if (req.body.accType > 3 || req.body.accType < 2) {
				failMessage(req, res, "非法注册");
				// 记录IP，告警
				return;
			}
			const existingUser = await Register.findOne({ root: req.body.root });
			if (existingUser) {
				failMessage(req, res, "该帐号已注册");
				return;
			}
			const masterAccount = await Register.findOne({ root: "master" });
			if (req.body.code !== masterAccount.code) {
				failMessage(req, res, "注册码错误");
				return;
			}
			Register.create(req.body).then(() => {
				successMessage(req, res, "创建");
				return;
			});
		} catch (err) {
			errMessage(req, res, err.message || "服务器错误");
			return;
		}
	});
};
